import React, { useState, useEffect } from 'react';
import produce from 'immer';
import XLSX from 'xlsx';
import { Spin } from 'antd';
import Tabs from '@/zero/components/Tabs';
import { request } from '@/zero/utils/axios';
import styles from './index.less';

const Index = props => {
  const { src, ...rest } = props;

  const [data, setData] = useState(null);

  useEffect(() => {
    if (src) {
      request(src, {
        responseType: 'arraybuffer',
      }).then(response => {
        if (response.success) {
          const workbook = XLSX.read(new Uint8Array(response.data), {
            type: 'array',
          });

          const newData = produce([], draftState => {
            // eslint-disable-next-line
            for (const [k, v] of Object.entries(workbook.Sheets)) {
              try {
                draftState.push({
                  name: k,
                  html: XLSX.utils.sheet_to_html(v),
                });
              } catch (e) {
                console.log(e);
              }
            }
            return draftState;
          });

          setData(newData);
        }
      });
    }
  }, [src]);

  return (
    <div {...rest}>
      {data ? (
        <Tabs
          tabPanes={data.map((item, index) => ({
            id: index,
            title: item.name,
            content: (
              <div className={styles.excel} dangerouslySetInnerHTML={{ __html: item.html }} />
            ),
          }))}
        />
      ) : (
        <Spin style={{ display: 'block', margin: '0 auto' }} />
      )}
    </div>
  );
};

Index.displayName = 'ExcelViewer';
export default Index;
